<div class="row">
    <aside class="profile-nav col-lg-3">
        <section>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="row">
                        <div class="col-lg-6">公司组织架构</div>
                        <div class="col-lg-6" style="font-size: 12px;text-align: right;padding-top: 4px;"><a href="javascript:void(0)" style="color: #FF6C60;" id="AddDepartment"><i class="icon-plus" style="margin-right: 5px;"></i>创建部门</a></div>
                    </div>
                </div>
                <div class="panel-body xsg-panel-body">
<!--                    <div>-->
<!--                        <button id="AddDepartment" class="btn btn-danger btn-sm">添加部门</button>-->
<!--                        <button id="AddPost" class="btn btn-warning btn-sm">添加职位</button>-->
<!--                    </div>-->
                    <div id="Organization"></div>

                </div>
            </div>
        </section>
    </aside>
    <div class="col-lg-9">
        <div class="row">
            <aside class="profile-info col-lg-12">
                <section>
                    <div class="panel panel-default">
                        <div id="StaffTableTitle" class="panel-heading">成员列表</div>
                        <div class="panel-body">
                            <table id="StaffList" lay-filter="StaffList" class="table"></table>
                            <script type="text/html" id="StaffHeadToolBar">
                                <div class="layui-btn-container">

                                </div>
                            </script>

                            <script type="text/html" id="StaffToolBar">
                                <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="change">变更</i> </a>
                            </script>
                        </div>
                    </div>
                </section>
            </aside>
        </div>
    </div>

</div>

<!-- 添加部门提示框 -->
<div id="AddDialog" style="display: none">
    <form class="form-horizontal" role="form">
        <div class="row" style="margin: 15px 15px;">

            <div class="form-group ">
                <label id="DepartmentLab" class="col-md-3 control-label">上级部门</label>
                <div class="col-md-9">
                    <select id="DepartmentID" class="form-control m-bot15">
                        <?php
                            foreach($DepartmentData as $Key => $Val){
                                $tID = $Val['ID'];
                                $tName = $Val['Name'];
                                echo "<option value='$tID'>$tName</option>";
                            }
                        ?>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label id="NameLab" class="col-md-3 control-label">部门名称</label>
                <div class="col-md-9">
                    <input id="Name" type="text" class="form-control" placeholder="">
                </div>
            </div>
            <div class="form-group">
                <label id="DescLab" class="col-md-3 control-label">部门描述</label>
                <div class="col-md-9">
                    <textarea id="Desc" class="form-control " name="comment" required></textarea>
                </div>
            </div>
        </div>
    </form>
</div>
<!-- 变更职位对话框 -->
<div id="ChangeDialog" style="display: none">
    <form class="form-horizontal" role="form">
        <div class="row" style="margin: 15px 15px;">

            <div class="form-group ">
                <label class="col-md-3 control-label">上级部门</label>
                <div class="col-md-9">
                    <select id="ChangeDepartmentID" class="form-control m-bot15">
                        <?php
                            foreach($DepartmentData as $Key => $Val){
                                $tID = $Val['ID'];
                                $tName = $Val['Name'];
                                echo "<option value='$tID'>$tName</option>";
                            }
                        ?>
                    </select>
                </div>
            </div>

            <div class="form-group ">
                <label class="col-md-3 control-label">职位</label>
                <div class="col-md-9">
                    <select id="ChangePostID" class="form-control m-bot15"></select>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
    var $, table;
    layui.use(['table', 'layer', 'jquery', 'tree'], function () {
        var layer = layui.layer,
            tree = layui.tree;

        table = layui.table;
        $ = layui.$;

        //请求组织结构
        mb_RequestOrganizationData(tree);

        //初始化职位和成员列表
        // mb_MemberOnClick(-1, );

        //添加部门按钮
        $('#AddDepartment').bind('click', function () {
            var dialogWidth = '650px';
            if (document.documentElement.scrollWidth < 500) {
                //手機版
                dialogWidth = '350px';
            }
            $('#DepartmentID').attr("disabled", false);
            $('#DepartmentLab').html('上级部门');
            $('#NameLab').html('部门名称');
            $('#DescLab').html('部门描述');

            layer.open({
                type: 1,
                title: '添加部门',
                area: [dialogWidth, '350px'],
                content: $('#AddDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['保存', '取消'],
                yes: function (index, layero) {
                    var PID = $('#DepartmentID').val();
                    var DepartmentName = $('#Name').val();
                    var DepartmentDesc = $('#Desc').val();
                    if (DepartmentName == '') {
                        layer.msg('请输入部门名称', {icon: 2});
                        return false;
                    }
                    var Params = {
                        CompanyID: {$CompanyID},
                        PID: PID,
                        Name: DepartmentName,
                        Describe: DepartmentDesc
                    }
                    var fields = {
                        Type: 'Department',
                        Params: JSON.stringify(Params)
                    };

                    global.post('/index.php/user/Event/mb_Add', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg(msg['msg'], {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                window.location.reload();
                            });
                            return false;
                        } else {
                            mb_OnMessage(msg);
                            return false;
                        }
                    });
                },
                btn2: function (index, layer0) {
                    console.log('取消按下');
                }
            });
        });

        //添加职位按钮
        $('#AddPost').bind('click', function () {
            var dialogWidth = '650px';
            if (document.documentElement.scrollWidth < 500) {
                //手機版
                dialogWidth = '350px';
            }
            $('#DepartmentID').attr("disabled", false);
            $('#DepartmentLab').html('部门');
            $('#NameLab').html('职位名称');
            $('#DescLab').html('职位描述');

            layer.open({
                type: 1,
                title: '添加职位',
                area: [dialogWidth, '350px'],
                content: $('#AddDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['保存', '取消'],
                yes: function (index, layero) {
                    var DepartmentID = $('#DepartmentID').val();
                    var PostName = $('#Name').val();
                    var PostDesc = $('#Desc').val();
                    if (PostName == '') {
                        layer.msg('请输入职位名称', {icon: 2});
                        return false;
                    }
                    var Params = {
                        DepartmentID: DepartmentID,
                        PID: 0,
                        Name: PostName,
                        Describe: PostDesc
                    }
                    var fields = {
                        Type: 'Post',
                        Params: JSON.stringify(Params)
                    };

                    global.post('/index.php/user/Event/mb_Add', fields, function (msg) {
                        if (msg['code'] == ErrCode_Normal) {
                            layer.msg(msg['msg'], {
                                offset: '15px'
                                , icon: 1
                                , time: 1000
                            }, function () {
                                window.location.reload();
                            });
                            return false;
                        } else {
                            mb_OnMessage(msg);
                            return false;
                        }
                    });
                },
                btn2: function (index, layer0) {
                    console.log('取消按下');
                }
            });
        });

        //监听员工数据表行工具事件
        table.on('tool(StaffList)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            console.log(data);

            $('#ChangeDepartmentID').val(data.DepartmentID);

            var fields = {
                DepartmentID: data.DepartmentID
            }
            global.post('/index.php/user/Department/mb_PostListing', fields, function (msg) {
                if (msg['code'] == ErrCode_Normal) {
                    $('#ChangePostID').find('option').remove();
                    for (var i = 0; i < msg['data'].length; i++) {
                        var val = msg['data'][i];
                        $('#ChangePostID').append("<option value='" + val.ID + "'>" + val.Name + "</option>");
                    }
                    $('#ChangePostID').val(data.PostID);
                    return false;
                } else {
                    mb_OnMessage(msg);
                    return false;
                }
            });

            var dialogWidth = '650px';
            if (document.documentElement.scrollWidth < 500) {
                //手機版
                dialogWidth = '350px';
            }

            if (layEvent === 'change') {
                layer.open({
                    type: 1,
                    title: '变更职位',
                    area: [dialogWidth, '350px'],
                    content: $('#ChangeDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    btn: ['保存', '取消'],
                    yes: function (index, layero) {

                        var DepartmentID = $('#ChangeDepartmentID').val();
                        var PostID = $('#ChangePostID').val();
                        var StaffID = data.ID;

                        var fields = {
                            StaffID: StaffID,
                            DepartmentID: DepartmentID,
                            PostID: PostID
                        }
                        global.post('/index.php/user/Department/mb_ChangeStaff', fields, function (msg) {
                            if (msg['code'] == ErrCode_Normal) {
                                layer.msg('保存成功', {
                                    offset: '15px'
                                    , icon: 1
                                    , time: 1000
                                }, function () {
                                    window.location.reload();
                                });
                                return false;
                            } else {
                                mb_OnMessage(msg);
                                return false;
                            }
                        });


                    },
                    btn2: function (index, layer0) {
                        console.log('取消按下');
                    }
                });
            }
        });

        //变更职位
        $('#ChangeDepartmentID').bind('change', function () {
            var DepartmentID = $('#ChangeDepartmentID').val();
            var fields = {
                DepartmentID: DepartmentID
            };
            global.post('/index.php/user/Department/mb_PostListing', fields, function (msg) {
                if (msg['code'] == ErrCode_Normal) {
                    $('#ChangePostID').find('option').remove();
                    for (var i = 0; i < msg['data'].length; i++) {
                        var val = msg['data'][i];
                        $('#ChangePostID').append("<option value='" + val.ID + "'>" + val.Name + "</option>");
                    }
                    return false;
                } else {
                    mb_OnMessage(msg);
                    return false;
                }
            });
        });
    });

    /**
     * 刷新职位和成员列表
     */
    function mb_MemberOnClick(ID, Name) {
        console.log("ID:" + ID + "  |  Name:" + Name);
        $('#StaffTableTitle').html(Name);
        table.render({
            elem: '#StaffList'
            , height: '723'
            , url: '/index.php/user/Department/mb_StaffListing' //数据接口
            , where: {
                DepartmentID: ID
            }
            // , page: true //开启分页
            , toolbar: '#StaffHeadToolBar' //开启头部工具栏，并为其绑定左侧模板
            , page: {
                theme: '#ff6c60'
            }
            , limit: 100
            , limits: [100, 200, 300, 400, 500]
            , cols: [[ //表头 總寬度1670
                {type: 'checkbox', fixed: 'left'}
                , {field: 'Name', title: '账号'}
                , {field: 'Nick', title: '姓名'}
                , {field: 'PostName', title: '职位'}
                , {title: '操作', width: 120, align: 'center', toolbar: '#StaffToolBar'}
            ]]
        });
    }

    function mb_EditOnClick(ID, PID, Name, Desc) {
        if (PID == 0) {
            console.log("最高级部门");
            $('#DepartmentID').val(ID);
            $('#DepartmentID').attr("disabled", true);
        } else {
            console.log("其他部门");
            $('#DepartmentID').val(PID);
            $('#DepartmentID').attr("disabled", false);
        }
        Name = Name.replace('|', '');
        console.log(Name);
        Name = Name.replaceAll('----', '');
        console.log(Name);

        $('#Name').val(Name);
        $('#Desc').val(Desc);

        var dialogWidth = '650px';
        if (document.documentElement.scrollWidth < 500) {
            //手機版
            dialogWidth = '350px';
        }

        layer.open({
            type: 1,
            title: '编辑部门',
            area: [dialogWidth, '350px'],
            content: $('#AddDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var DepartmentID = $('#DepartmentID').val();
                var DepartmentName = $('#Name').val();
                var DepartmentDesc = $('#Desc').val();
                if (DepartmentName == '') {
                    layer.msg('请输入部门名称', {icon: 2});
                    return false;
                }
                var Params = {};
                if (PID == 0) {
                    Params = {
                        ID: ID,
                        CompanyID: {$CompanyID},
                        PID: 0,
                        Name: DepartmentName,
                        Describe: DepartmentDesc
                    };
                } else {
                    Params = {
                        ID: ID,
                        CompanyID: {$CompanyID},
                        PID: DepartmentID,
                        Name: DepartmentName,
                        Describe: DepartmentDesc
                    };
                }

                var fields = {
                    Type: 'Department',
                    Params: JSON.stringify(Params)
                };

                global.post('/index.php/user/Event/mb_Edit', fields, function (msg) {
                    if (msg['code'] == ErrCode_Normal) {
                        layer.msg(msg['msg'], {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        }, function () {
                            window.location.reload();
                        });
                        return false;
                    } else {
                        mb_OnMessage(msg);
                        return false;
                    }
                });
            },
            btn2: function (index, layer0) {
                console.log('取消按下');
            }
        });
    }

    /**
     * 删除按下
     */
    function mb_DeleteOnClick(ID) {
        var fields = {
            ID: ID
        };
        global.post('/index.php/user/Department/mb_DeleteDepartment', fields, function (msg) {
            if (msg['code'] == ErrCode_Normal) {
                layer.msg(msg['msg'], {
                    offset: '15px'
                    , icon: 1
                    , time: 1000
                }, function () {
                    window.location.reload();
                });
                return false;
            } else {
                mb_OnMessage(msg);
                return false;
            }
        });
    }

    function mb_RequestOrganizationData(tree) {
        global.post('/index.php/user/Department/mb_GetDepartmentList', {}, function (msg) {
            if (msg['code'] == ErrCode_Normal) {
                //渲染
                tree.render({
                    elem: '#Organization'  //绑定元素
                    , data: msg['data']
                    , onlyIconControl: true
                    ,click: function(obj){
                        // layer.msg(JSON.stringify(obj.data));
                        // 点击部门，刷新用户表
                        mb_MemberOnClick(obj.data.id, obj.data.title);
                    }
                });
                mb_MemberOnClick(msg['data'][0]['id'], msg['data'][0]['title']);
                return false;
            } else {
                mb_OnMessage(msg);
                return false;
            }
        });
    }

    function mb_ShowAddDepartment(layer) {
        var dialogWidth = '650px';
        if (document.documentElement.scrollWidth < 500) {
            //手機版
            dialogWidth = '350px';
        }
        $('#DepartmentID').attr("disabled", false);
        $('#DepartmentLab').html('上级部门');
        $('#NameLab').html('部门名称');
        $('#DescLab').html('部门描述');

        layer.open({
            type: 1,
            title: '添加部门',
            area: [dialogWidth, '350px'],
            content: $('#AddDialog'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var PID = $('#DepartmentID').val();
                var DepartmentName = $('#Name').val();
                var DepartmentDesc = $('#Desc').val();
                if (DepartmentName == '') {
                    layer.msg('请输入部门名称', {icon: 2});
                    return false;
                }
                var Params = {
                    CompanyID: {$CompanyID},
                    PID: PID,
                    Name: DepartmentName,
                    Describe: DepartmentDesc
                }
                var fields = {
                    Type: 'Department',
                    Params: JSON.stringify(Params)
                };

                global.post('/index.php/user/Event/mb_Add', fields, function (msg) {
                    if (msg['code'] == ErrCode_Normal) {
                        layer.msg(msg['msg'], {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        }, function () {
                            window.location.reload();
                        });
                        return false;
                    } else {
                        mb_OnMessage(msg);
                        return false;
                    }
                });
            },
            btn2: function (index, layer0) {
                console.log('取消按下');
            }
        });
    }
</script>

<style>
    .layui-icon-subtraction:before {
        content: "\e67e";
        position: absolute;
        right: -1px;
    }

    .layui-icon-addition:before {
        content: "\e624";
        position: absolute;
        right: -1px;
    }

    @media screen and (min-width: 1200px) {
        .xsg-panel-body{
            height: 783px;
        }
    }
</style>